package com.zziq.cloudpicturebank.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.qcloud.cos.utils.IOUtils;
import com.zziq.cloudpicturebank.annotation.AuthCheck;
import com.zziq.cloudpicturebank.api.aliyunAi.AliYunAiApi;
import com.zziq.cloudpicturebank.api.aliyunAi.model.CreateOutPaintingTaskResponse;
import com.zziq.cloudpicturebank.api.aliyunAi.model.GetOutPaintingTaskResponse;
import com.zziq.cloudpicturebank.api.imagesearch.baidu.ImageSearchApiFacade;
import com.zziq.cloudpicturebank.api.imagesearch.baidu.model.ImageSearchResult;
import com.zziq.cloudpicturebank.api.imagesearch.so.model.SoImageSearchResult;
import com.zziq.cloudpicturebank.api.imagesearch.so.sub.SoImageSearchApiFacade;
import com.zziq.cloudpicturebank.common.BaseResponse;
import com.zziq.cloudpicturebank.common.DeleteRequest;
import com.zziq.cloudpicturebank.common.ResultUtils;
import com.zziq.cloudpicturebank.constant.UserConstant;
import com.zziq.cloudpicturebank.exception.BusinessException;
import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.exception.ThrowUtils;
import com.zziq.cloudpicturebank.manager.auth.SpaceUserAuthManager;
import com.zziq.cloudpicturebank.manager.auth.model.StpKit;
import com.zziq.cloudpicturebank.manager.auth.annotation.SaSpaceCheckPermission;
import com.zziq.cloudpicturebank.manager.auth.model.SpaceUserPermissionConstant;
import com.zziq.cloudpicturebank.model.dto.picture.*;
import com.zziq.cloudpicturebank.model.dto.user.UserCanDownloadCountRequest;
import com.zziq.cloudpicturebank.model.entity.Picture;
import com.zziq.cloudpicturebank.model.entity.Space;
import com.zziq.cloudpicturebank.model.entity.User;
import com.zziq.cloudpicturebank.model.enums.PictureReviewStatusEnum;
import com.zziq.cloudpicturebank.model.enums.UserRoleEnum;
import com.zziq.cloudpicturebank.model.vo.picture.PictureDownloadResponse;
import com.zziq.cloudpicturebank.model.vo.picture.PictureTagCategory;
import com.zziq.cloudpicturebank.model.vo.picture.PictureVO;
import com.zziq.cloudpicturebank.model.vo.user.UserCanDownloadCountReponse;
import com.zziq.cloudpicturebank.service.PictureService;
import com.zziq.cloudpicturebank.service.SpaceService;
import com.zziq.cloudpicturebank.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import org.springframework.web.util.UriUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @ClassName PictureController
 * @Description
 * @Created by ZZIQ
 **/
@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {
    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    /**
     * 上传图片（可重新上传）--本地文件上传
     */
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO
                = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 上传图片（可重新上传）--url路径上传
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        PictureVO pictureVO = pictureService.uploadPicture(
                pictureUploadRequest.getFileUrl(),
                pictureUploadRequest,
                loginUser);

        return ResultUtils.success(pictureVO);
    }

    /**
     * 批量上传图片（网页抓取）
     *
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch
    (@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest, HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }


    /**
     * 删除图片
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deleteRequest.getId(), loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员可用）
     *
     * @param pictureUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                               HttpServletRequest request) {
        Long pictureId = pictureUpdateRequest.getId();
        if (pictureUpdateRequest == null || pictureId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = pictureService.updatePicture(pictureUpdateRequest, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类）
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");

        Space space = null;
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        //判断该图片是否属于私人空间图片
        if (picture.getSpaceId() != null) {
            //判断图片的分享时间是否已过期
            //获取当前时间
            Date now = new Date();
            //如果过期时间大于当前时间，则表示未过期
            if (picture.getShareExpireTime() != null && picture.getShareExpireTime().after(now)) {
                return ResultUtils.success(pictureVO);
            }
            //校验权限
            ThrowUtils.throwIf(picture.getReviewStatus() == PictureReviewStatusEnum.REJECT.getValue(), ErrorCode.NO_AUTH_ERROR, "管理员审核拒绝通过该图片");
            boolean res = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!res, ErrorCode.NO_AUTH_ERROR, "无权限访问该图片");
            space = spaceService.getById(picture.getSpaceId());
        }
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        //定义返回对象
        Page<Picture> picturePage;
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
            // 查询数据库
            picturePage = pictureService.page(new Page<>(current, size),
                    pictureService.getQueryWrapper(pictureQueryRequest));
        } else {
            // 私有空间
            //校验权限
            boolean res = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!res, ErrorCode.NO_AUTH_ERROR, "图片不属于公共图库中的图片，你没有该空间权限");

            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 查询数据库
            picturePage = pictureService.page(new Page<>(current, size),
                    pictureService.getQueryWrapper(pictureQueryRequest));
            //过滤掉审核被拒绝的（通过或待审核可查看）
            List<Picture> pictureList
                    = picturePage.getRecords()
                    .stream()
                    .filter(picture -> picture.getReviewStatus() != PictureReviewStatusEnum.REJECT.getValue())
                    .collect(Collectors.toList());
            picturePage.setRecords(pictureList);
        }
        // 获取封装类,并返回
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }


    /**
     * 本接口 仅限于访问主页时获取首页图片信息
     * 分页获取图片封装类（本地缓存+redis缓存）
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 普通用户默认只能查看已过审的数据
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "该图片不属于公共图库中的图片，你没有该空间权限");
            }
        }
        return ResultUtils.success
                (pictureService.listPictureVOByPageWithCache(pictureQueryRequest, request));
    }

    /**
     * 编辑图片（给用户使用）
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }


    /**
     * 审核图片（给管理员使用）
     *
     * @param pictureReviewRequest
     * @param request
     * @return
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 以图搜图
     */
    @PostMapping("/search/picture/so")
    public BaseResponse<List<SoImageSearchResult>> searchPictureByPictureIsSo(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        final long TWO_MB = 4 * 1024 * 1024L; // 限制搜索的图片大小最大为 2MB
        ThrowUtils.throwIf(oldPicture.getPicSize() > TWO_MB, ErrorCode.PARAMS_ERROR,
                "搜索的图片大小不能超过2MB");
        List<SoImageSearchResult> resultList = new ArrayList<>();
        int start = 0;
        //最多返回50条数据
        while (resultList.size() <= 50) {
            List<String> soImageUrl = new ArrayList<>();
            List<SoImageSearchResult> tempList = SoImageSearchApiFacade.searchImage(
                    StrUtil.isNotBlank(oldPicture.getOriginUrl()) ?
                            oldPicture.getOriginUrl() : oldPicture.getUrl(), start, soImageUrl
            );

            if (tempList.isEmpty()) {
                break;
            }
            resultList.addAll(tempList);
            start += tempList.size();
        }

        return ResultUtils.success(resultList);
    }


    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    @Deprecated
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        return ResultUtils.success(resultList);
    }

    /**
     * 根据颜色（主色调）搜图
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = pictureQueryRequest.getPicColor();
        Long spaceId = pictureQueryRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        if ("".equals(picColor)) {
            List<PictureVO> pictureVOList = pictureService.lambdaQuery()
                    .eq(Picture::getSpaceId, spaceId)
                    .list()
                    .stream()
                    .map(PictureVO::objToVo)
                    .collect(Collectors.toList());
            return ResultUtils.success(pictureVOList);
        }
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 更新分享过期时间(当前时间+5分钟)
     *
     * @param pictureUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update/shareExpireTime")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<Boolean> updateShareExpireTime(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                                       HttpServletRequest request) {
        //参数校验
        ThrowUtils.throwIf(pictureUpdateRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = pictureUpdateRequest.getId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        User loginUser = userService.getLoginUser(request);
        //权限校验
//        ThrowUtils.throwIf(!Objects.equals(picture.getUserId(), loginUser.getId()), ErrorCode.NO_AUTH_ERROR);
        //1.获取过期时间（当前时间+5分钟）
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(5);
        //2.将过期时间expireTime 转换为Date对象
        Date expireTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        //3.更新数据库中的过期时间字段
        picture.setShareExpireTime(expireTime);
        return ResultUtils.success(pictureService.updateById(picture));
    }

    /**
     * 批量编辑图片
     *
     * @param pictureEditByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }

    @PostMapping("/download")
    public void downloadPicture(@RequestBody PictureDownloadRequest pictureDownloadRequest,
                                HttpServletRequest request,
                                HttpServletResponse response) throws IOException {
        Long pictureId = pictureDownloadRequest.getId();
        Picture picture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        pictureService.downloadPicture(picture, loginUser, pictureDownloadRequest.isCompress(), response);
        userService.lambdaUpdate()
                .eq(User::getId, loginUser.getId())
                .setSql("downloadCount = downloadCount - 1")
                .update();
    }

}
